#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import requests
import json

class Auth401Debugger:
    def __init__(self, base_url="http://localhost:8080/api"):
        self.base_url = base_url
        self.session = requests.Session()
        self.access_token = None
        self.test_content_id = None
        
    def get_token(self):
        """获取登录token"""
        url = f"{self.base_url}/auth/login"
        data = {
            "usernameOrEmail": "admin2",
            "password": "123456"
        }
        
        response = self.session.post(url, json=data)
        if response.status_code == 200:
            result = response.json()
            if result.get('success'):
                self.access_token = result['data']['token']
                print(f"✅ 登录成功")
                return True
        
        print(f"❌ 登录失败: {response.text}")
        return False
    
    def find_test_content_id(self):
        """获取一个测试内容ID"""
        url = f"{self.base_url}/contents/my"
        headers = {'Authorization': f'Bearer {self.access_token}'}
        
        response = self.session.get(url, params={"page": 0, "size": 1}, headers=headers)
        if response.status_code == 200:
            result = response.json()
            if result.get('success') and result['data']['content']:
                self.test_content_id = result['data']['content'][0]['id']
                print(f"✅ 找到测试内容ID: {self.test_content_id}")
                return True
        
        print("❌ 无法找到测试内容")
        return False
    
    def test_content_navigation(self):
        """测试内容导航接口"""
        print("\n🔍 测试内容导航接口（应该是公开的）...")
        
        if not self.test_content_id:
            print("  ❌ 没有测试内容ID")
            return
        
        url = f"{self.base_url}/contents/{self.test_content_id}/navigation"
        
        # 测试1：不带认证
        print("  测试1：不带认证头")
        try:
            response = self.session.get(url, timeout=10)
            print(f"    状态码: {response.status_code}")
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    print(f"    ✅ 成功（不需要认证）")
                    return
            print(f"    响应: {response.text[:200]}")
        except Exception as e:
            print(f"    异常: {str(e)}")
        
        # 测试2：带认证
        print("  测试2：带认证头")
        headers = {'Authorization': f'Bearer {self.access_token}'}
        try:
            response = self.session.get(url, headers=headers, timeout=10)
            print(f"    状态码: {response.status_code}")
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    print(f"    ✅ 成功（需要认证）")
                    return
            print(f"    响应: {response.text[:200]}")
        except Exception as e:
            print(f"    异常: {str(e)}")
    
    def test_like_count(self):
        """测试获取点赞数接口"""
        print("\n🔍 测试获取点赞数接口（应该是公开的）...")
        
        if not self.test_content_id:
            print("  ❌ 没有测试内容ID")
            return
        
        url = f"{self.base_url}/contents/{self.test_content_id}/likes/count"
        
        # 测试1：不带认证
        print("  测试1：不带认证头")
        try:
            response = self.session.get(url, timeout=10)
            print(f"    状态码: {response.status_code}")
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    count = result.get('data', 0)
                    print(f"    ✅ 成功，点赞数: {count}")
                    return
            print(f"    响应: {response.text[:200]}")
        except Exception as e:
            print(f"    异常: {str(e)}")
        
        # 测试2：带认证
        print("  测试2：带认证头")
        headers = {'Authorization': f'Bearer {self.access_token}'}
        try:
            response = self.session.get(url, headers=headers, timeout=10)
            print(f"    状态码: {response.status_code}")
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    count = result.get('data', 0)
                    print(f"    ✅ 成功，点赞数: {count}")
                    return
            print(f"    响应: {response.text[:200]}")
        except Exception as e:
            print(f"    异常: {str(e)}")
    
    def test_comments_list(self):
        """测试获取评论列表接口"""
        print("\n🔍 测试获取评论列表接口（应该是公开的）...")
        
        if not self.test_content_id:
            print("  ❌ 没有测试内容ID")
            return
        
        url = f"{self.base_url}/contents/{self.test_content_id}/comments"
        
        # 测试1：不带认证
        print("  测试1：不带认证头")
        try:
            response = self.session.get(url, params={"page": 0, "size": 10}, timeout=10)
            print(f"    状态码: {response.status_code}")
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    count = len(result['data']['content'])
                    print(f"    ✅ 成功，评论数: {count}")
                    return
            print(f"    响应: {response.text[:200]}")
        except Exception as e:
            print(f"    异常: {str(e)}")
        
        # 测试2：带认证
        print("  测试2：带认证头")
        headers = {'Authorization': f'Bearer {self.access_token}'}
        try:
            response = self.session.get(url, params={"page": 0, "size": 10}, headers=headers, timeout=10)
            print(f"    状态码: {response.status_code}")
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    count = len(result['data']['content'])
                    print(f"    ✅ 成功，评论数: {count}")
                    return
            print(f"    响应: {response.text[:200]}")
        except Exception as e:
            print(f"    异常: {str(e)}")
    
    def test_comment_count(self):
        """测试获取评论数接口"""
        print("\n🔍 测试获取评论数接口（应该是公开的）...")
        
        if not self.test_content_id:
            print("  ❌ 没有测试内容ID")
            return
        
        url = f"{self.base_url}/contents/{self.test_content_id}/comments/count"
        
        # 测试1：不带认证
        print("  测试1：不带认证头")
        try:
            response = self.session.get(url, timeout=10)
            print(f"    状态码: {response.status_code}")
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    count = result.get('data', 0)
                    print(f"    ✅ 成功，评论数: {count}")
                    return
            print(f"    响应: {response.text[:200]}")
        except Exception as e:
            print(f"    异常: {str(e)}")
        
        # 测试2：带认证
        print("  测试2：带认证头")
        headers = {'Authorization': f'Bearer {self.access_token}'}
        try:
            response = self.session.get(url, headers=headers, timeout=10)
            print(f"    状态码: {response.status_code}")
            if response.status_code == 200:
                result = response.json()
                if result.get('success'):
                    count = result.get('data', 0)
                    print(f"    ✅ 成功，评论数: {count}")
                    return
            print(f"    响应: {response.text[:200]}")
        except Exception as e:
            print(f"    异常: {str(e)}")
    
    def run_debug(self):
        """运行调试"""
        print("🔧 HTTP 401 问题调试工具")
        print("=" * 50)
        
        # 1. 登录
        if not self.get_token():
            return
        
        # 2. 获取测试内容ID
        if not self.find_test_content_id():
            return
        
        # 3. 测试所有返回401的接口
        self.test_content_navigation()
        self.test_like_count()
        self.test_comments_list()
        self.test_comment_count()
        
        print("\n✅ 调试完成!")

if __name__ == "__main__":
    debugger = Auth401Debugger()
    debugger.run_debug() 